<template>
  <div>
    <!-- 头部 -->
    <myDivider :name="scene == 'add' ? '新增报事' : '修改报事'"></myDivider>
    <el-page-header @back="goBack">
    </el-page-header>

    <!-- 表单 -->
    <el-form :rules="rules" ref="ruleForm" class="fromStyle" :model="formData" label-width="150px">
      <div style="display: flex;" v-if="scene == 'update'">
        <el-form-item label="报事日期：">
          <div style="width: 222px;">
            {{ formData.eventDay }}
          </div>
        </el-form-item>
        <el-form-item label="事件编号：">
          <div style="width: 222px;">
            {{ formData.eventsNumber }}
          </div>
        </el-form-item>
      </div>
      <div style="display: flex;">
        <el-form-item label="报事类别：" prop="category">
          <el-select @change="categoryChange" style="width: 222px;" v-model="formData.category" placeholder="请选择报事类别">
            <el-option label="报修" value="1"></el-option>
            <el-option label="咨询" value="2"></el-option>
            <el-option label="建议" value="3"></el-option>
            <el-option label="表扬" value="4"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="formData.category == '1'" label="服务类别：" prop="serviceCategory">
          <el-select style="width: 222px;" class="ok" v-model="formData.serviceCategory" placeholder="请选择服务类别">
            <el-option label="电路" value="1"></el-option>
            <el-option label="电器" value="2"></el-option>
            <el-option label="主体结构" value="3"></el-option>
            <el-option label="给排水" value="4"></el-option>
            <el-option label="综合类" value="5"></el-option>
          </el-select>
        </el-form-item>
      </div>

      <el-form-item label="报事区域：" prop="region">
        <div class="ok">
          <myCascader v-if="myCascaderShow" :defaultVal="defaultVal" :props="props" @getData="myCascaderGetData">
          </myCascader>
        </div>
      </el-form-item>

      <el-form-item label="客户信息：" prop="customerId">
        <div style="display: flex;justify-content: space-between;width:596px ;">
          <el-input style="width: 300px;" placeholder="客户姓名" disabled v-model="formData.customerName"></el-input>
          <el-input style="width: 222px;" placeholder="客户手机号" disabled v-model="formData.phone"></el-input>
          <el-button type="primary" @click="selectPopUser">搜索</el-button>
        </div>
      </el-form-item>


      <el-form-item label="经办人：" prop="" required>
        <el-input disabled style="width: 222px;" v-model="formData.userName"></el-input>
      </el-form-item>
      <el-form-item label="报事方式：" prop="eventWay">
        <el-select class="ok" v-model="formData.eventWay" placeholder="请选择报事方式">
          <el-option label="来访" value="1"></el-option>
          <el-option label="呼叫中心" value="2"></el-option>
          <el-option label="内容人员反馈" value="3"></el-option>
          <el-option label="客户端" value="4"></el-option>
          <el-option label="其它渠道" value="5"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="预约时间：">
        <div style="width: 594px;display: flex;justify-content: space-between;">
          <el-date-picker style="width: 222px;" ref="Time" value-format="yyyy-MM-dd" v-model="formData.reservationDay"
            type="date" placeholder="选择日期" :picker-options="pickerOptions" @change="Timechange">
          </el-date-picker>
          <el-select :disabled="!formData.reservationDay" style="width: 360px;" v-model="formData.reservationInterval"
            placeholder="请选择时间">
            <el-option v-for="item, i in TimeSelect" :key="i" :label="item.val" :value="item.val"
              :disabled="item.disabled">
            </el-option>
          </el-select>
        </div>
      </el-form-item>

      <el-form-item label="报事内容：" prop="description">
        <el-input class="ok" rows="5" show-word-limit maxlength="200" type="textarea" v-model="formData.description"
          placeholder="请输入内容，不超过200字"></el-input>
      </el-form-item>

      <el-form-item label="图片：" prop="imgs">
        <MyUploadImgNotDetele v-if="myNewUploadShow" :id="uploadId" @getImgList="getImgList"
          @deleteImgList="deleteImgList" :EchoImgList="EchoImgList" uploadUrl="/business/events/uploadImg">
        </MyUploadImgNotDetele>
      </el-form-item>

      <el-form-item class="btn">
        <el-button style="width: 100px;" type="primary" @click="onSubmit('ruleForm')">{{ scene == 'add' ? '添加' : "更改"
          }}</el-button>
        <el-button style="width: 100px;" type="info" @click="$router.go(-1)">取消</el-button>
      </el-form-item>
    </el-form>
    <!-- 客户列表 -->
    <div class="dialogStyle">
      <el-dialog title="客户列表" :visible.sync="userPopShow" width="650px" @close="close" :close-on-click-modal="false">
        <div style="display: flex;justify-content: space-around;">
          <el-input clearable style="width: 250px;" maxlength="11" type="text" v-model="keyphone"
            placeholder="用户手机号"></el-input>
          <el-input clearable style="width: 250px;" maxlength="5" type="text" v-model="keyname"
            placeholder="用户姓名"></el-input>
          <el-button type="primary" @click="searchForName">搜索</el-button>
        </div>
        <el-table highlight-current-row ref="elTable" :data="popUserData" style="width: 100%;margin-top: 20px"
          height="400px">
          <el-table-column prop="account" label="手机号" width="180">
          </el-table-column>
          <el-table-column prop="userName" label="姓名" width="180">
          </el-table-column>
          <el-table-column prop="roomName" label="住址">
          </el-table-column>
          <el-table-column label="确认选择">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" plain @click="ChangeUser(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>


  </div>
</template>

<script>
import axios from '@/api/axios.js'
import myCascader from '@/components/myCascader.vue'
import MyUploadImgNotDetele from '@/components/upload/MyUploadImgNotDetele.vue'

export default {
  components: {
    MyUploadImgNotDetele,
    myCascader
  },
  data() {
    return {
      props: {
        value: 'id',
        label: 'name',
        lazy: true,
        lazyLoad: async (node, resolve) => {
          console.log(node, '级联选择器');
          const { level } = node;
          if (level == 0) {
            let res = await this.$api.events.getCellList(
              {
                name: '',
                pageNum: 1,
                pageSize: 10000,
                roleIds: this.logOnUser.roleIds
              })
            if (res.code == 200) {
              console.log(res.data.list, 'ahhh');
              resolve(res.data.list)

            } else {
              this.$message.error(res.message)
            }
          } else if (level == 1) {
            // 获取楼宇列表
            let res = await this.$api.events.getBuildingList({
              "residentialQuartersId": node.path[0]
            })
            if (res.code == 200) {
              res.data.list.push({
                name: '公共区域',
                id: 0,
                leaf: true
              })
              resolve(res.data.list)
            } else {
              this.$message.error(res.message)
            }
          } else if (level == 2) { //获取单元列表
            let res = await this.$api.axios.post('/business/room/getUnitCodeListByBuildingId', {
              "buildingId": node.path[1]
            })
            if (res) {
              let arr = []
              res.data.forEach(el => {
                arr.push({
                  name: el.name,
                  id: el.value,
                })
              })
              resolve(arr)
            }
          } else if (level == 3) { //获取楼层
            let res = await this.$api.axios.post('/business/room/getFloorsListByBuildingId', {
              "buildingId": node.path[1], //楼宇id  必填
              "unitCode": node.path[2]
            })
            if (res) {
              let arr = []
              res.data.forEach(el => {
                arr.push({
                  name: el.name,
                  id: el.value,
                })
              })
              resolve(arr)
            }
          } else if (level == 4) {
            let res = await this.$api.axios.post('/business/room/getRoomListByFloors', {
              "buildingId": node.path[1], //楼宇id  必填
              "unitCode": node.path[2],
              "floors": node.path[3] //楼层  必填
            })
            if (res) {
              if (res.data.length > 0) {
                let arr = []
                res.data.forEach(el => {
                  arr.push({ ...el, leaf: true })
                })
                resolve(arr)
              } else {
                resolve([{
                  name: '暂无房间',
                  id: 0,
                  disabled: true,
                  leaf: true
                }])
              }

            }
          }else{
            resolve()
          }

        }
      },
      defaultVal: '',
      myCascaderShow: false,
      logOnUser: {},
      pickerOptions: {
        disabledDate(time) {
          let a = time.getTime()
          let b = Date.now() - 8.64e7
          let is = a < b
          return is;
        },
      },
      TimeSelect: [
        { val: '08:00:00~09:00:00', disabled: false },
        { val: '09:00:00~10:00:00', disabled: false },
        { val: '10:00:00~11:00:00', disabled: false },
        { val: '11:00:00~12:00:00', disabled: false },
        { val: '14:00:00~15:00:00', disabled: false },
        { val: '15:00:00~16:00:00', disabled: false },
        { val: '16:00:00~17:00:00', disabled: false },
        { val: '17:00:00~18:00:00', disabled: false },
      ],
      defaTimeShow: true,
      // 场景？？更新还是新增
      scene: '',
      formData: {
      },

      rules: {
        category: [
          { required: true, message: '请选择报事类别', trigger: 'change' }
        ],
        serviceCategory: [
          { required: true, message: '请选择服务类别', trigger: 'change' }
        ],
        region: [
          { required: true, message: '请选择区域', trigger: 'change' }
        ],
        customerId: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        eventWay: [
          { required: true, message: '请选择报事方式', trigger: 'change' }
        ],
        // reservationDay: [
        //   { required: true, message: '请输入预约时间', trigger: 'blur' }
        // ],
        description: [
          { required: true, message: '请输入报事内容', trigger: 'blur' }
        ],
      },
      // 点击搜索弹窗后的用户列表
      popUserData: [],
      userPopShow: false,
      keyphone: '',
      keyname: '',
      //  回显的图片路径
      EchoImgList: [],
      myNewUploadShow: false,
      uploadId: 0,
      deleteImg: [],
    }
  },

  async activated() {





    // 表单相关
    this.formData = {}
    this.logOnUser = JSON.parse(sessionStorage.getItem('logOnUser'))
    this.scene = this.$route.query.type
    if (this.scene == 'add') {
      this.initializationForm()
    } else if (this.scene == 'update') {

      let res = await this.$api.events.EventDetail(this.$route.query.id)
      console.log(res, '事件详情')
      if (res.code != 200) {
        this.$message.error(res.message)
        return
      }
      // 处理图片
      this.deleteImg = []
      this.uploadId = res.data.id
      if (res.data.imgs == null) {
        this.EchoImgList = []
        this.$set(this.formData, 'imgs', [])
      } else {
        this.EchoImgList = res.data.imgs
        this.$set(this.formData, 'imgs', res.data.imgs)
      }
      this.myNewUploadShow = false
      setTimeout(() => {
        this.myNewUploadShow = true
      }, 500);



      let data = res.data
      this.myCascaderShow = false
      if (data.isPublic == 1) { //公共区域
        this.defaultVal = `${data.residentialName}/公共区域`
        this.$set(this.formData, 'region', [data.residentialId, 0])
      } else { //私人区域
        this.defaultVal = `${data.residentialName}/${data.buildingName}/${data.unitCode}/${data.floors}/${data.roomName}`
        this.$set(this.formData, 'region', [data.residentialId, data.buildingId, data.unitCode, data.floors, data.roomId])
      }
      setTimeout(() => {
        this.myCascaderShow = true
      }, 50)
      this.$set(this.formData, 'id', data.id)
      this.$set(this.formData, 'category', data.category)
      this.$set(this.formData, 'serviceCategory', data.serviceCategory)
      this.$set(this.formData, 'eventDay', data.eventDay)
      this.$set(this.formData, 'eventsNumber', data.eventsNumber)
      this.$set(this.formData, 'unitId', data.unitId)
      this.$set(this.formData, 'unitType', data.unitType)
      this.$set(this.formData, 'customerId', data.customerId)
      this.$set(this.formData, 'customerName', data.customerName)
      this.$set(this.formData, 'phone', data.phone)
      this.$set(this.formData, 'userName', this.logOnUser.name)
      this.$set(this.formData, 'eventWay', data.eventWay)
      this.$set(this.formData, 'reservationDay', data.reservationDay)
      this.$set(this.formData, 'reservationInterval', data.reservationInterval)
      this.$set(this.formData, 'description', data.description)
      if (data.reservationDay) {
        // 获取时间段下拉列表
        this.getSelectTime(data.reservationDay)
      }
    }
    this.$nextTick(() => {
      this.$refs['ruleForm'].clearValidate()
    })
  },
  methods: {
    goBack(){
      this.$confirm('返回后不保存，确认返回吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.go(-1)
      }).catch(() => {

      });
    
    },
    // 搜索弹窗用户列表
    async selectPopUser() {

      if (this.formData.region.length == 0) {
        this.$message.error('请选择报事区域');
        return
      }
      let res = await this.$api.events.getRoomUserList({
        roomId: this.formData.region[4] ? this.formData.region[4] : 0,
        account: this.popKeyPhone,
        userName: this.popKeyName,
        residentialId: this.formData.region[0],
      })
      if (res.code == 200) {
        this.userPopShow = true
        this.popUserData = res.data
        // 高亮选中项
        this.$nextTick(() => {
          this.popUserData.forEach(el => {
            if (el.id == this.formData.customerId) {
              this.$refs.elTable.setCurrentRow(el)
            }
          })
        })
      } else {
        this.$message.error(res.message)
      }


    },
    initializationForm() { //初始化数据
      // 图片相关
      this.deleteImg = []
      this.EchoImgList = []
      this.uploadId = 0
      this.myNewUploadShow = false
      setTimeout(() => {
        this.myNewUploadShow = true
      }, 500);



      this.myCascaderShow = false
      this.defaultVal = ''
      setTimeout(() => {
        this.myCascaderShow = true
      }, 50)

      this.$set(this.formData, 'category', '')
      this.$set(this.formData, 'serviceCategory', '')
      this.$set(this.formData, 'region', [])
      this.$set(this.formData, 'customerId', '')
      this.$set(this.formData, 'customerName', '')
      this.$set(this.formData, 'phone', '')
      this.$set(this.formData, 'userName', this.logOnUser.name)
      this.$set(this.formData, 'eventWay', '')
      this.$set(this.formData, 'reservationDay', '')
      this.$set(this.formData, 'reservationInterval', '')
      this.$set(this.formData, 'description', '')
      this.$set(this.formData, 'imgs', [])
      this.$set(this.formData, 'unitId', this.logOnUser.unitId)
      this.$set(this.formData, 'unitType', this.logOnUser.unitType)
    },
    myCascaderGetData(e) {
      this.$set(this.formData, 'customerId', '')
      this.$set(this.formData, 'customerName', '')
      this.$set(this.formData, 'phone', '')
      console.log(e, '级联选择器的值')
      this.$set(this.formData, 'region', e.ids)
    },
    categoryChange(e) {
      // this.$set(this.formData, 'region', [])
      // this.$set(this.formData, 'customerId', '')
      // this.$set(this.formData, 'customerName', '')
      // this.$set(this.formData, 'phone', '')
      this.$set(this.formData, 'serviceCategory', '')
      this.$nextTick(() => {
        this.$refs['ruleForm'].clearValidate()
      })

    },
    getSelectTime(e) {
      const today = new Date();
      const inputDate = new Date(e);
      today.setHours(0, 0, 0, 0);
      inputDate.setHours(0, 0, 0, 0);
      // 如果是今天，那么把今天之前的时间都设为不可选
      if (today.toISOString().slice(0, 10) === inputDate.toISOString().slice(0, 10)) {
        let time = new Date()
        this.TimeSelect.forEach(el => {
          el.disabled = time.getHours() >= el.val.slice(0, 2)
        })
      } else {
        this.TimeSelect.forEach(el => {
          el.disabled = false
        })
      }
    },
    // 点击日期后，时间筛选
    Timechange(e) {
      if (!e) {
        this.$set(this.formData, 'reservationDay', '')
      }
      this.$set(this.formData, 'reservationInterval', '')
      this.getSelectTime(e)
    },
    // 当前要上传的图片列表
    getImgList(val) {
      console.log('当前选择的图片', val)
      this.formData.imgs = val
    },
    deleteImgList(val) {
      this.deleteImg.push(val)
    },
    // 选择用户列表
    ChangeUser(row) {
      console.log(row, '选择的用户');
      this.userPopShow = false
      this.$set(this.formData, "customerId", row.id);
      this.$set(this.formData, "customerName", row.userName);
      this.$set(this.formData, "phone", row.account);
    },
    //关闭弹窗事件
    close() {
      // 清空搜索内容
      this.keyphone = ''
      this.keyname = ''
    },

    // 根据手机号或用户名搜索用户列表
    searchForName() {
      this.selectPopUser()
    },

    onSubmit(formName) {
      if (this.scene == 'add') { //新增！！新增！！新增！！新增！！新增！！新增！！新增！！新增！！
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('是否提交?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async () => {
              this.deleteImg.forEach(async (el) => {
                let res = await this.$api.ImgFile.delete(defaultUrl + '/business/events/deleteImg', {
                  "picName": el
                })
              })
              if (this.formData.region.length == 2) { //说明是公共区域
                //如果是公共区域
                this.formData.isPublic = 1
                this.formData.buildingId = 0
                this.formData.roomId = 0
              } else if (this.formData.region.length == 5) { //说明是私人区域
                this.formData.isPublic = 0
                this.formData.buildingId = this.formData.region[1]
                this.formData.roomId = this.formData.region[4]
              }
              this.formData.residentialId = this.formData.region[0]


              this.$api.events.AddEvent(this.formData).then(res => {
                console.log(res, '请求的数据')
                if (res.code == 200) {

                  this.$message({
                    message: '添加成功',
                    type: 'success'
                  });
                  this.$router.push('/events/eventsDetail?id=' + res.data.id)

                } else {
                  this.$message.error(res.message)
                }
              }).catch(err => {
                console.log(err);
              })
            }).catch(() => {

            });

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      } else if (this.scene == 'update') {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('是否确认修改?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async () => {
              this.deleteImg.forEach(async (el) => {
                let res = await this.$api.ImgFile.delete(defaultUrl + '/business/events/deleteImg', {
                  "picName": el
                })
              })
              if (this.formData.region.length == 2) { //说明是公共区域
                //如果是公共区域
                this.formData.isPublic = 1
                this.formData.buildingId = 0
                this.formData.roomId = 0
              } else if (this.formData.region.length == 5) { //说明是私人区域
                this.formData.isPublic = 0
                this.formData.buildingId = this.formData.region[1]
                this.formData.roomId = this.formData.region[4]
              }
              // 把roomId获取到
              this.formData.residentialId = this.formData.region[0]


              this.$api.events.UpdateEvent(this.formData).then(res => {
                if (res.code != 200) {
                  this.$message.error(res.message)
                  return
                }
                console.log(res)
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
                this.$router.push('/events/eventsDetail?id=' + res.data.id)
              }).catch(err => {
                console.log(err);
              })
            }).catch(() => {

            });


          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }

    }
  },

  deactivated() {
    this.EchoImgList = []
    this.myNewUploadShow = false
    for (let a in this.formData) {
      this.formData[a] = null
    }

  },
}
</script>

<style lang="less" scoped>
.Timestyle {
  position: relative;

  /deep/ .is-disabled {
    .el-input__inner {
      background-color: white;
      color: black;
    }
  }

  >span {
    position: absolute;
    right: 160px;
    top: 50%;
    transform: translateY(-50%);
  }
}

.fromStyle {
  margin: 50px 0 0 50px;
  width: 750px;
}

// 所有的input宽度
.ok {
  width: 594px;
}

.smallok {
  width: 163px;
}

// 添加取消按钮
.btn {
  position: fixed;
  bottom: 10px;
  right: 70px;
}
</style>